from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.appointment.space import appointment_space_controller
from app.controllers.jobs.jobs_log  import jobs_log_controller
from app.controllers.jobs.jobs_rule import jobs_rule_controller
from app.models import JobsRule
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.jobs import JobsLogCreate, JobsLogUpdate

jobs_log_router = APIRouter()
model_name = "定时执行记录"


@jobs_log_router.get("/list", summary=f"查看{model_name}列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
        job_id: int = Query(0, description="任务名称"),
):
    q = Q()
    if start_time and end_time:
        q &= Q(time__range=[start_time, end_time])
    elif start_time:
        q &= Q(time__gte=start_time)
    elif end_time:
        q &= Q(time__lte=end_time)
    if job_id:
        q &= Q(job_id=job_id)
    jobs_objs = await jobs_rule_controller.level_list()
    total, data = await jobs_log_controller.do_list(page=page, page_size=page_size, search=q)
    for item in data:
        item['job_name'] = jobs_objs.get(item['job_id'], '已删除的任务')
        if item['result_status'] == 1:
            item['result_status'] = "执行成功"
        else:
            item['result_status'] = "执行失败"
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@jobs_log_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await jobs_log_controller.do_detail(data_id=data_id)
    return Success(data=data)

@jobs_log_router.post("/create", summary=f"创建{model_name}")
async def do_create(
        category_in: JobsLogCreate,
):
    await jobs_log_controller.do_create(obj_in=category_in)
    return Success(msg="创建成功")

@jobs_log_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        category_in: JobsLogUpdate,
):
    await jobs_log_controller.do_update(obj_in=category_in)
    return Success(msg="更新成功")

@jobs_log_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await jobs_log_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@jobs_log_router.get("/jobs_rule", summary="获取所有任务名")
async def list_jobs_rule():
    level_objs = await jobs_rule_controller.level_list()
    data = []
    for level in level_objs:
        if level:
            data.append({"label": level_objs[level], "value": level})
    return Success(data=data)




